<template>
	<el-dialog v-model="dialog" :title="!state.form.id ? '新增' : '修改'" width="60%" :before-close="handleClose">
		<el-form ref="formRef" :model="state.form" :rules="state.rules" label-width="120px" @keyup.enter="submitForm(formRef)" status-icon>
	    				<el-form-item label="PK" prop="id">
					<el-input v-model="state.form.id" placeholder="PK"></el-input>
				</el-form-item>
					<el-form-item label="优惠券id" prop="couponId">
						<ma-dict-select v-model="state.form.couponId" dict-type="gift_cash_status" placeholder="优惠券id"></ma-dict-select>
					</el-form-item>
				<el-form-item label="商品id" prop="spuId">
					<el-input v-model="state.form.spuId" placeholder="商品id"></el-input>
				</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="handleClose">关 闭</el-button>
				<el-button type="primary" :loading="loading" @click="submitForm(formRef)">确 认</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage,FormInstance } from 'element-plus'
import { addObj, editObj, getById } from '/@/api/dev/devdemo'
const emit = defineEmits(['initPage']);
const state = reactive({
	form: {
		id: '',
		couponId: '',
		spuId: '',
		createTime: '',
		updateTime: '',
		delFlag: '',
		tenantId: '',
		createBy: '',
		updateBy: ''	},
	rules: {
		couponId: [{ required: true, message: '必填项不能为空', trigger: 'change' }],
		spuId: [{ required: true, message: '必填项不能为空', trigger: 'change' }]	},
})


const dialog = ref(false);
const loading = ref(false);
const formRef = ref();

const initForm = (row: any | undefined) => {
	dialog.value = true;
	if (row && row.id) {
		getDetail(row.id);
	}
};

const getDetail = (id: string) => {
	loading.value = true;
	getById(id).then((response: any) => {
		state.form = response.data.data;
		loading.value = false;
	});
};

/**
 * 关闭事件
 */
const handleClose = () => {
	resetForm(formRef.value);
};

/**
 * 重置表单
 */
const resetForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	state.form.id = '';
	loading.value = false;
	dialog.value = false;
	formEl.resetFields();
};


/**
 * 提交按钮
 */
const submitForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid) => {
		if (valid) {
			loading.value = true;
			if (state.form.id) {
				//修改
				edit();
			} else {
				//新增
				add();
			}
		}
	});
};
/**
 * 新增
 */
const add = () => {
	addObj(state.form)
			.then(() => {
				resetForm(formRef.value);
				ElMessage.success('新增成功');

				emit('initPage');
			})
			.catch(() => {
				loading.value = false;
			});
};
/**
 * 修改
 */
const edit = () => {
	editObj(state.form)
			.then(() => {
				resetForm(formRef.value);
				ElMessage.success('修改成功');
				emit('initPage');
			})
			.catch(() => {
				loading.value = false;
			});
};

defineExpose({
	initForm
})
</script>
